<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-select
        v-if="!shop"
        v-model="listQuery.shopId"
        clearable
        class="filter-item"
        :placeholder="$t('请选择门店')"
      >
        <el-option
          v-for="item in shops"
          :value="item.id"
          :label="item.name"
        ></el-option>
      </el-select>

      <el-date-picker
        v-model="listQuery.dateRange"
        type="datetimerange"
        class="filter-item"
        start-placeholder="请选择开始时间"
        end-placeholder="请选择结束时间"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        clearable
        :picker-options="{ shortcuts: datePickerShortcuts }"
      >
      </el-date-picker>

      <el-select
        v-model="listQuery.orderSource"
        placeholder="请选择"
        class="filter-item"
        clearable
      >
        <el-option
          v-for="item in orderSourceList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >{{ $t("Search") }}
      </el-button>
    </div>

    <el-card class="box-card">
      <h4>{{ $t("Summary") }}</h4>
      <div class="table-layout">
        <el-row>
          <el-col :span="3" class="table-cell-title">{{
            $t("订单总数")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("交易总额")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("退款总额")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("销售总额")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("税费总交易总额")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("税费总交易明细")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("税费总退款总额")
          }}</el-col>
          <el-col :span="3" class="table-cell-title">{{
            $t("税费总退款明细")
          }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="3" class="table-cell">{{
            totalStatistics.totalCount
          }}</el-col>
          <el-col :span="3" class="table-cell"
            >${{
              (totalStatistics.totalAmount + totalStatistics.refundTotalAmount)
                | floorTwoDecimal
            }}</el-col
          >
          <el-col :span="3" class="table-cell"
            >${{ totalStatistics.refundTotalAmount | floorTwoDecimal }}</el-col
          >
          <el-col :span="3" class="table-cell"
            >${{
              (totalStatistics.totalAmount +
                totalStatistics.refundTotalAmount -
                totalStatistics.refundTotalAmount)
                | floorTwoDecimal
            }}</el-col
          >
          <el-col :span="3" class="table-cell"
            >${{ totalStatistics.taxTotalAmount | floorTwoDecimal }}</el-col
          >
          <el-col :span="3" class="table-cell">
            <div v-for="tax in totalStatistics.taxDetailLs" :key="tax.code">
              {{ tax.code }}：${{ tax.totalAmount | floorTwoDecimal }}
            </div>
          </el-col>
          <el-col :span="3" class="table-cell"
            >${{
              totalStatistics.taxRefundTotalAmount | floorTwoDecimal
            }}</el-col
          >
          <el-col :span="3" class="table-cell">
            <div
              v-for="tax in totalStatistics.taxRefundDetailLs"
              :key="tax.code"
            >
              {{ tax.code }}：${{ tax.totalAmount | floorTwoDecimal }}
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="box-card">
      <h4>{{ $t("Details") }}</h4>
      <!-- 查询结果 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        :element-loading-text="$t('Searching')"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          type="index"
          :index="getIndex"
          width="50"
        ></el-table-column>

        <el-table-column align="center" :label="$t('日期')" prop="date" />

        <el-table-column
          align="center"
          :label="$t('订单总数')"
          prop="totalCount"
        />

        <el-table-column
          align="center"
          :label="$t('订单总额')"
          prop="totalAmount"
        >
          <template slot-scope="scope">
            {{ scope.row.totalAmount | floorTwoDecimal }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('税费总额')"
          prop="taxTotalAmount"
        >
          <template slot-scope="scope">
            {{ scope.row.taxTotalAmount | floorTwoDecimal }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          property="taxDetailLs"
          :label="$t('税费详情')"
        >
          <template slot-scope="scope">
            <div v-for="tax in scope.row.taxDetailLs" :key="tax.code">
              {{ tax.code }}: {{ tax.totalAmount | floorTwoDecimal }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('Operate')"
          width="300"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-dropdown trigger="click" @command="handleHourDetail">
              <el-button
                v-permission="['GET /admin/p/order_hour_statistics']"
                icon="el-icon-time"
                type="success"
                size="small"
              >
                {{ $t("时间")
                }}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{ row: scope.row, time: 60 }">{{
                  $t("60-minute")
                }}</el-dropdown-item>
                <el-dropdown-item :command="{ row: scope.row, time: 45 }">{{
                  $t("45-minute")
                }}</el-dropdown-item>
                <el-dropdown-item :command="{ row: scope.row, time: 30 }">{{
                  $t("30-minute")
                }}</el-dropdown-item>
                <el-dropdown-item :command="{ row: scope.row, time: 15 }">{{
                  $t("15-minute")
                }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <!--            <el-button v-permission="['GET /admin/order/order_hour_statistics']"icon="el-icon-time" type="success" size="small"
              @click="handleHourDetail(scope.row)">{{ $t('15-minute') }}</el-button>-->
            <el-button
              v-permission="['GET /admin/p/order_day_detail']"
              type="primary"
              size="small"
              @click="handleDetail(scope.row)"
              >{{ $t("Details") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </el-card>

    <el-card class="box-card">
      <el-alert title="消息提示:必须选择门店、时间间隔、日期再点击生成！" type="info" show-icon>
      </el-alert>
      <h4>{{$t('小时对比折线图')}}</h4>

      <el-select
        v-if="!shop"
        v-model="listLineQuery.shopId"
        clearable
        class="filter-item"
        :placeholder="$t('请选择门店')"
      >
        <el-option
          v-for="item in shops"
          :value="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-select v-model="listLineQuery.time" placeholder="请选择">
        <el-option
          v-for="item in timeList"
          :key="item.time"
          :label="$t(item.label)"
          :value="item.time">
        </el-option>
      </el-select>
      <el-date-picker
        v-model="listLineQuery.searchDateList"
        type="dates"
        value-format="yyyy-MM-dd"
        placeholder="选择日期">
      </el-date-picker>
      <el-button icon="el-icon-search" @click="getOrderHourStatisticsLine" >{{$t('生成图表')}}</el-button>
      <el-empty v-if="lineList.length==0" description="根据提示操作生成图表📊"></el-empty>
      <OrderTrendChart v-if="lineList.length!=0" :lineList="lineList" />
    </el-card>
  </div>
</template>

<script>
import { allForPerm } from "@/api/shop";
import { orderTotalStatistics, shopOrderDayDetail ,orderHourStatisticsLine} from "@/api/order";
import BackToTop from "@/components/BackToTop";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import store from "@/store";
import OrderTrendChart from './orderTrendChart.vue';
export default {
  name: "orderStoreStatisticsDay",
  components: {
    BackToTop,
    Pagination,
    OrderTrendChart
  },
  data() {
    return {
      timeList:[{time: 60,label:'60-minute'},{time: 45,label:'45-minute'},{time: 30,label:'30-minute'},{time: 15,label:'15-minute'}],
      listLineQuery: {
        time:15,
        shopId: undefined,
        searchDateList:[],
      },
      lineList: [],
      // 当前店铺
      shop: store.state.user.shop,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        shopId: undefined,
        shopName: undefined,
        dateRange:[],
        // 订单来源
        orderSource: undefined,
      },
      totalStatistics: {},
      list: [],
      shops: [],
      orderSourceList: [
        {
          value: "1",
          label: this.$t("Phone_App"),
        },
        {
          value: "2",
          label: this.$t("Store_Order"),
        },
        {
          value: "3",
          label: this.$t("Online_Mall"),
        },
        {
          value: "4",
          label: this.$t("Subscription"),
        },
      ],
      datePickerShortcuts: [
        {
          text: '最近一小时',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(end.getTime() - 3600 * 1000);
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '今天',
          onClick(picker) {
            const start = new Date(new Date().setHours(0, 0, 0, 0));
            const end = new Date();
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setDate(end.getDate() - 7);
            picker.$emit('pick', [start, end]);
          }
        }
      ],
    };
  },
  created() {
    this.listQuery.dateRange[0] = this.getFirstDayOfMonth(this.getVancouverDate()); //当月第一天
    this.listQuery.dateRange[1]  = this.getVancouverDate();

    if (this.shop) {
      this.listQuery.shopId = this.shop.id;
      this.getList();
    } else {
      allForPerm().then((response) => {
        this.shops = response.data.data.list;
        this.listQuery.shopId = this.shops[0].id;

        this.getList();
      });
    }

    this.getOrderHourStatisticsLine();
  },
  methods: {
    //获取数据
    getOrderHourStatisticsLine(){
      orderHourStatisticsLine(this.listLineQuery)
        .then((response) => {
          this.lineList = response.data.data;
        })
        .catch(() => {
          this.lineList = [];
        });
    },
    getList() {
      // 汇总查询
      orderTotalStatistics(this.listQuery)
        .then((response) => {
          this.totalStatistics = response.data.data;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });

      shopOrderDayDetail(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.getList();
    },
    handleHourDetail(data) {
      let query = {
        shopId: this.listQuery.shopId,
        searchDate: data.row.date,
        time: data.time,
      };
      this.$router.push({
        path: "/statistics/order_statistics_hour",
        query: query,
      });
    },
    handleDetail(row) {
      let query = {
        shopId: this.listQuery.shopId,
        searchDate: row.date,
      };
      this.$router.push({
        path: "/statistics/order_statistics_day_detail",
        query: query,
      });
    },
    getFullDate(targetDate) {
      var D, y, m, d;
      if (targetDate) {
        D = new Date(targetDate);
        y = D.getFullYear();
        m = D.getMonth() + 1;
        d = D.getDate();
      } else {
        y = fullYear;
        m = month;
        d = date;
      }
      m = m > 9 ? m : "0" + m;
      d = d > 9 ? d : "0" + d;
      return y + "-" + m + "-" + d;
    },
    formatDate(date) {
      var d = new Date(date),
        month = "" + (d.getMonth() + 1),
        day = "" + d.getDate(),
        year = d.getFullYear();

      if (month.length < 2) month = "0" + month;
      if (day.length < 2) day = "0" + day;

      return [year, month, day].join("-");
    },
    //获取加拿大温哥华的当前时间
    getVancouverDate() {
      const options = {
        timeZone: "America/Vancouver",
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false,
      };
      const parts = new Intl.DateTimeFormat("en-CA", options).formatToParts(new Date());
      const dateParts = {};
      parts.forEach(({ type, value }) => {
        dateParts[type] = value;
      });
      return `${dateParts.year}-${dateParts.month}-${dateParts.day} ${dateParts.hour}:${dateParts.minute}:${dateParts.second}`;
    },
    //获取加拿大温哥华当月第一天的时间
    getFirstDayOfMonth(dateString) {
      // 创建一个新的 Date 对象
      const date = new Date(dateString);
      // 将日期设置为月份的第一天
      date.setDate(1);
      // 获取年月日并返回，并设置为00:00:00
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day} 00:00:00`;
    },

    getIndex(index) {
      return index + 1 + (this.listQuery.page - 1) * this.listQuery.limit;
    },
  },
};
</script>

<style scoped>
.table-layout {
  margin-top: 20px;
}

.table-cell {
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  overflow: hidden;
}

.table-cell-title {
  padding: 10px;
  background: #f2f6fc;
  text-align: center;
  font-size: 14px;
  color: #303133;
}
</style>
